<template>
  <div class="edit-articles">
    <section class="head">
      <el-form
        :inline="true"
        :model="ruleForm"
        :rules="rules"
        ref="refRuleForm"
      >
        <el-form-item prop="title">
          <el-input
            placeholder="标题"
            clearable
            size="mini"
            v-model="ruleForm.title"
          >
            <template #prefix>
              <i class="el-input__icon el-icon-edit"></i>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item prop="notebook">
          <el-input
            placeholder="笔记本"
            clearable
            size="mini"
            v-model="ruleForm.notebook"
          >
            <template #prefix>
              <i class="el-input__icon el-icon-notebook-2"></i>
            </template>
          </el-input>
        </el-form-item>
      </el-form>
    </section>
    <section class="left">
      <el-input
        type="textarea"
        placeholder="请输入内容"
        resize="none"
        v-model="textarea"
      >
      </el-input>
    </section>
    <section class="right">
      <div v-html="htmlRendered"></div>
    </section>
    <section>
      <div class="save" @click="save"><span>保存</span></div>
      <div class="cancel" @click="cancelConfirm"><span>取消</span></div>
    </section>
  </div>
</template>
<script lang="ts">
import renderMarkDown from "@/config/marked";
import {
  defineComponent,
  ref,
  reactive,
  computed,
  toRefs,
  onMounted,
  onUnmounted,
} from "@vue/runtime-core";
import { uuid } from "@/utils/index";
import { setArticle, getNotebookList, getArticle } from "@/api/index";
import { ElMessage, ElMessageBox } from "element-plus";
import { useStore } from "vuex";
import { useRouter } from "vue-router";

export default defineComponent({
  setup(props, context) {
    const store = useStore();
    const router = useRouter();
    const refRuleForm = ref<any>(null);
    const reactiveData = reactive({
      dialogVisible: false,
      ruleForm: {
        title: "",
        notebook: "",
      },
      textarea: "",
      aid: 0,
      rules: {
        title: [{ required: true, message: "请输入标题", trigger: "blur" }],
        notebook: [
          { required: true, message: "请输入笔记本名称", trigger: "blur" },
        ],
      },
    });

    const htmlRendered = computed(() => {
      return renderMarkDown(reactiveData.textarea);
    });

    function init() {
      window.history.pushState("", "");
      window.addEventListener("popstate", popListener);
      window.onbeforeunload = beforeUnload;

      if (store.state.isCreating) {
        reactiveData.aid = uuid();
      } else {
        getArticle(
          store.state.articleId || window.localStorage.getItem("aid")
        ).then((res: any) => {
          const { code, data } = res;
          if (code === 200) {
            reactiveData.aid = data.article.aid;
            reactiveData.ruleForm.title = data.article.title;
            reactiveData.textarea = data.article.content;
            reactiveData.ruleForm.notebook = data.article.notebookName;
          }
        });
      }
    }

    function save() {
      refRuleForm.value.validate(async (valid: any) => {
        if (valid) {
          const article = {
            title: reactiveData.ruleForm.title,
            notebookName: reactiveData.ruleForm.notebook,
            content: reactiveData.textarea,
            aid: reactiveData.aid,
          };
          console.log(await setArticle(article));
          console.log(article);
          ElMessage.success({
            message: "保存成功",
            type: "success",
          });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    }

    function cancelConfirm(): void {
      ElMessageBox.confirm(
        "确定离开当前页面吗？未保存的数据将不会保留",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(() => {
          router.push({ name: "Home" });
        })
        .catch();
    }

    function popListener() {
      window.history.pushState("", "");
      cancelConfirm();
    }

    function beforeUnload(e: any) {
      window.localStorage.setItem("aid", reactiveData.aid.toString());

      e.returnValue = "";
      return "";
    }

    init();

    onMounted(() => {
      getNotebookList().then((res) => {
        console.log(res);
      });
    });

    //必须在组件销毁时解除事件监听，否则多次进入编辑页会重复触发确认弹窗
    onUnmounted(() => {
      window.removeEventListener("popstate", popListener);
      window.onbeforeunload = null;
    });

    return {
      ...toRefs(reactiveData),
      save,
      htmlRendered,
      cancelConfirm,
      refRuleForm,
    };
  },
});
</script>

<style lang="scss" scoped>
.edit-articles {
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
  align-items: center;
  align-content: space-around;
  width: 100%;
  height: 100%;
  background-image: url("https://i.loli.net/2021/06/04/8ChdSApQV2tJ4z3.jpg");
  background-size: 100% 100%;

  .head {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 100%;
    :deep() .el-input {
      flex-basis: 10%;
    }
  }

  .left {
    width: 45%;
    height: 90%;
    overflow: hidden;
    background-color: rgb(194, 194, 194);
    border-radius: 20px 0 0 20px;

    :deep() .el-textarea {
      ::-webkit-scrollbar {
        width: 5px;
        height: 5px;
      }
      ::-webkit-scrollbar-track {
        border-radius: 10px;
        background-color: #949191;
      }
      ::-webkit-scrollbar-thumb {
        border-radius: 10px;
        background-color: rgb(71, 71, 71);
      }
      height: 100%;
      textarea {
        padding: 20px;
        height: 100%;
        font-family: Microsoft Yahei, Lato, Lucida Grande, Lucida Sans Unicode,
          Lucida Sans, Verdana, Tahoma, sans-serif;
        font-size: 16px;
        color: #000;
        border: hidden;
      }
    }
  }
  .right {
    box-sizing: border-box;
    padding: 0 20px;
    width: 45%;
    height: 90%;
    color: #fff;
    overflow: auto;
    background-color: #555050;
    border-radius: 0 20px 20px 0;
    pre {
      margin-top: 20px;
      white-space: pre-wrap;
      word-wrap: break-word;
      word-break: normal;
      font-family: Microsoft Yahei, Lato, Lucida Grande, Lucida Sans Unicode,
        Lucida Sans, Verdana, Tahoma, sans-serif;
    }
  }

  .save {
    position: fixed;
    left: 0;
    bottom: 0;
    width: 100px;
    height: 100px;
    opacity: 0;
    background-color: #20345f;
    clip-path: polygon(0 0, 100% 100%, 0 100%);
    transition: opacity 0.1s ease;

    span {
      z-index: 1;
      position: relative;
      left: 15px;
      top: 60px;
      color: #fff;
    }
    &:hover {
      opacity: 1;
    }
  }

  .cancel {
    position: absolute;
    right: 0;
    top: 0;
    width: 100px;
    height: 100px;
    opacity: 0;
    background-color: rgb(128, 9, 0);
    clip-path: polygon(0 0, 100% 0, 100% 100%);
    transition: all 0.1s ease;

    span {
      z-index: 1;
      position: relative;
      left: 55px;
      top: 20px;
      color: #fff;
    }

    &:hover {
      opacity: 1;
    }
  }

  :deep() .el-dialog {
    border-radius: 20px;
  }
}
</style>
